
var LavasCore = require('lavas-core-vue')
var express = require('express')
var stoppable = require('stoppable')
var proxy = require('http-proxy-middleware')

// var targetUrl = 'http://157.255.237.145:9980/Dev/' // 开发

var configPath = './lavas.config.js'
// fix https://github.com/lavas-project/lavas/issues/50
if (process.argv.length >= 3 && process.argv[2] !== 'dev') {
    configPath = process.argv[2]
}

var targetUrl = 'http://39.108.232.35:10110/Vanjn' //万京服务器

var proxyTable = {
    // proxy table example
    '/api': {
        // filter: ['/api', '/download'],
        target: targetUrl,
        changeOrigin: true
    },
    // 'invoke': {
    //   filter: (pathname, req) => {
    //     return pathname.match('^(\/proxy)(\/[1-9a-zA-Z\.]+)*(\.(img|jdn|jup|vdt|vdp))?$')
    //   },
    //   pathRewrite: {
    //     '^/proxy': ''
    //   },
    //   target: targetUrl,
    //   changeOrigin: true
    // }
}

var port = process.env.PORT || 3000
var core = new LavasCore(__dirname)
var app
var server

/**
 * start dev server
 */
function startDevServer() {
    app = express()
    core.build()
        .then(function () {
            // API Proxying during development
            Object.keys(proxyTable).forEach(function (pattern) {
                app.use(pattern, proxy(proxyTable[pattern]))
            })

            app.use(core.expressMiddleware())

            /**
             * server.close() only stop accepting new connections,
             * we need to close existing connections with help of stoppable
             */
            server = stoppable(app.listen(port, function () {
                console.log('server started at localhost:' + port)
            }))
        })
        .catch(function (err) {
            console.log(err)
        })
}

/**
 * every time lavas rebuild, stop current server first and restart
 */
core.on('rebuild', function () {
    core.close().then(function () {
        server.stop()
        startDevServer()
    })
})

core.init(process.env.NODE_ENV || 'development', true, {configPath})
    .then(function () {
        startDevServer()
    })

// catch promise error
process.on('unhandledRejection', function (err) {
    console.warn(err)
})
